using WebRtcProject.Services;

namespace WebRtcProject.Services
{
    /// <summary>
    /// Consul 初始化后台服务
    /// 负责在应用启动时初始化Consul连接和服务注册
    /// </summary>
    public class ConsulInitializationService : BackgroundService
    {
        private readonly ConsulService _consulService;
        private readonly ILogger<ConsulInitializationService> _logger;

        public ConsulInitializationService(
            ConsulService consulService,
            ILogger<ConsulInitializationService> logger)
        {
            _consulService = consulService;
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                _logger.LogInformation("正在初始化 Consul 服务发现和配置管理...");
                
                // 初始化Consul连接
                await _consulService.InitializeAsync();
                
                _logger.LogInformation("Consul 服务发现和配置管理初始化完成");

                // 可选：设置一些初始配置
                await SetupInitialConfigsAsync();

                // 不使用 Timeout.Infinite，而是使用循环等待
                while (!stoppingToken.IsCancellationRequested)
                {
                    await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
                }
            }
            catch (OperationCanceledException)
            {
                _logger.LogInformation("Consul 初始化服务正常停止");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Consul 服务初始化失败");
                // 不抛出异常，让应用继续运行（Consul为可选功能）
            }
        }

        /// <summary>
        /// 设置初始配置（可选）
        /// </summary>
        private async Task SetupInitialConfigsAsync()
        {
            try
            {
                _logger.LogInformation("设置初始Consul配置...");

                // 设置一些基础配置
                var initialConfigs = new Dictionary<string, string>
                {
                    { "webrtc/info/version", "1.0.0" },
                    { "webrtc/info/environment", Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development" },
                    { "webrtc/info/machine", Environment.MachineName },
                    { "webrtc/info/startup_time", DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss UTC") }
                };

                foreach (var config in initialConfigs)
                {
                    try
                    {
                        // 添加小延迟，避免太快的连续请求
                        await Task.Delay(100);
                        
                        var success = await _consulService.SetConfigValueAsync(config.Key, config.Value);
                        if (success)
                        {
                            _logger.LogDebug("设置初始配置成功: {Key} = {Value}", config.Key, config.Value);
                        }
                        else
                        {
                            _logger.LogWarning("设置初始配置失败: {Key}", config.Key);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, "设置配置项失败: {Key}", config.Key);
                        // 继续处理下一个配置项
                    }
                }

                _logger.LogInformation("初始Consul配置设置完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设置初始Consul配置失败");
            }
        }

        public override void Dispose()
        {
            _consulService?.Dispose();
            base.Dispose();
        }
    }
} 